<%-- 
   * 【描 述】：菜单管理页面
   * 【环 境】：JAVA 1.7.0_13
   *  @author         柴志鹏  CHAIZP@GMAIL.COM
   *  @version        v1.0 2014-06-05
   *  @since          2014-06-05
 --%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ include file="/include/head.jsp"%>
<html>
  <head>
    <title>菜单管理</title>
    <link rel="stylesheet" type="text/css" href="<%=cssPath%>/icon.css" />
    <style type="text/css">
    	.c-tree-node-red span {
    		color: red !important;
    	}
    </style>
    <script type="text/javascript">
    	Ext.onReady(function(){
    		Ext.QuickTips.init();
	    	Ext.form.Field.prototype.msgTarget = 'qtip';
	    	
	    	var panel;
    		var viewport = new Ext.Viewport({
	            layout: 'border',
	            items:[{
	                region: 'west',
	                id: 'west-panel',
	                title: '菜单管理',
	                split: true,
	                width: 200,
	                //minSize: 175,
	                //maxSize: 400,
	                collapsible: true,
	                //margins:'0 0 0 0',
	                //cmargins:'0 0 0 0',
	                layout: 'accordion',
	                layoutConfig: {
	                    animate: true
	                },
	                items: [new Ext.Panel({
			                title: '用户菜单',
			                collapsed: false,
			                items: [new TreePanel({
			                	id: 'userMenuTree',
			                	menuType: '1'
			                })],
			                listeners: {
			            		beforeexpand: function() {//展开前
	                				Ext.getCmp('formPanel').getForm().reset();
			            			Ext.getCmp('menuType').setValue('1');
			            		}
			                }
			            }), new Ext.Panel({
			                title: '设置菜单',
			                collapsed: true,
			                items: [new TreePanel({
			                	id: 'settingsMenuTree',
			                	menuType: '2'
			                })],
			                listeners: {
			            		beforeexpand: function() {//展开前
			            			Ext.getCmp('formPanel').getForm().reset();
			            			Ext.getCmp('menuType').setValue('2');
			            		}
			                }
			        	})
	                ]
	            },{
	                region: 'center',
	                layout: 'column',
	                autoScroll: true,
	                frame: true,//背景色
	                items: [new Ext.form.FormPanel({
					            id:'formPanel',
					            region: 'center',
					            autoScroll: true,
					            layout: 'column',
					            labelWidth: 100,
					            labelAlign: "right",
					            width: '500',
					            height: '330',
					            //bodyStyle: 'padding:0px 0px 0',
					            border: false,
					            frame: false,
					            fileUpload: true,
					            buttonAlign: 'center',
					            layout: 'form',
					            items:[{
					            	html: '<p>节点信息</p>',
					            	style: 'font-size: 20px; text-align: center; padding: 5 5 5 5'
					            },
					            new Ext.form.TextField({// 文本
									fieldLabel: '菜单名称',
									anchor: '90%',
									name: 'text',
									id: 'menuName',
									readOnly: true
								}),
								new Ext.form.TextField({// 文本
									fieldLabel: '自身节点代码',
									anchor: '90%',
									name: 'id',
									id: 'nodeCode',
									readOnly: true
								}),
								new Ext.form.TextField({// 文本
									fieldLabel: '父节点代码',
									anchor: '90%',
									name: 'pid',
									id: 'parentCode',
									readOnly: true
								}),
								new Ext.form.TextField({// 文本
									fieldLabel: '连接地址',
									anchor: '90%',
									id: 'linkAddress',
									readOnly: true
								}),
								new Ext.form.RadioGroup({// 单选按钮
									fieldLabel:'使用状态',
									anchor: '90%',
									id: 'status',
									disabled: true,
									columns: [50,50],// 列间距
			            			items: [
			            				{boxLabel: '启用', inputValue: 1, name: 'status', checked: true},
			            				{boxLabel: '禁用', inputValue: 0, name: 'status'}
			            			]
								}),
								new Ext.form.TextField({// 文本
									fieldLabel: 'Icon样式',
									anchor: '90%',
									id: 'iconCls',
									readOnly: true
								}),
								new Ext.form.TextArea({
									fieldLabel: '备注',
									anchor: '90%',
									id: 'remark',
									readOnly: true
								}),
								new Ext.form.Hidden({
					            	id: 'menuType',
					            	value: '1'//1=用户菜单/2=设置菜单
					            }),
								new Ext.form.Hidden({//节点信息
					            	id: 'leaf'
					            })],
								buttons: [{
									id: 'addBtn',
					                text: '新增',
					                handler: function() {
										var menuPid = Ext.getCmp('nodeCode').getValue();
										var menuType = Ext.getCmp('menuType').getValue();
										executeBatch('C', '添加节点', menuType, menuPid);
					                }
					            },{
					            	id: 'modifyBtn',
					                text: '修改',
					                handler: function() {
					            		var menuId = Ext.getCmp('nodeCode').getValue();
										if(menuId) {
											var menuPid = Ext.getCmp('parentCode').getValue();
											var menuName = Ext.getCmp('menuName').getValue();
											var menuType = Ext.getCmp('menuType').getValue();
						                    executeBatch('U', '修改节点', menuType, menuPid, menuId, menuName);
										} else {
											Ext.MessageBox.alert('提示', '请选择要修改的节点!');
										}
					                }
					            },{
					            	id: 'deleteBtn',
					                text: '删除',
					                handler: function() {
					            		var nodeId = Ext.getCmp('nodeCode').getValue();
					            		if(nodeId != '') {
					            			if(Ext.getCmp('leaf').getValue() != 'true') {
					            				Ext.MessageBox.alert('提示','该节点具有子节点,请先删除子节点.');
					            				return false;
					            			}
					            			
					            			Ext.MessageBox.confirm('提示', '确定删除此节点?', 
						                    	function(flag){
						                    		if(flag == 'yes') {
						                    			Ext.Ajax.request({
									                        url: 'MenuAction!menuOperator.do',
									                        method: 'POST',
									                        params: {
									                        	'cudType': 'D',//Delete
									                        	'menu.id': nodeId,
									                        	'menu.pid': Ext.getCmp('parentCode').getValue()
									                        },
									                        success: function(result, request){
									                        	refresh();
									                        },
									                        failure: function(result, request){
									                            Ext.Msg.alert('提示','操作失败!请重试.');
									                        }
									                    });
						                    		}
						                    	}
						                    );
					            		} else {
					            			Ext.MessageBox.alert('提示','请选择要删除的节点!');
					            		}
					                }
					            }]
		            		})]
	            }]
	        });
    		
    	});
    	
    	function executeBatch(cudType, title, menuType, pid, id, menuName) {
    		var menuUrl;
    		var enableStatus;
    		var iconCls = 'icon-grid';
    		var remark;
    		if(cudType == 'U') {//修改
    			menuUrl = Ext.getCmp('linkAddress').getValue();
    			enableStatus = Ext.getCmp('status').getValue().inputValue.toString();
    			iconCls = Ext.getCmp('iconCls').getValue();
    			remark = Ext.getCmp('remark').getValue();
    		}
    		
    		var form = new Ext.form.FormPanel({
	            id: 'formBatch',
	            region: 'center',
	            autoScroll: true,
	            layout: 'form',
	            labelWidth: 70,
	            labelAlign: 'right',
	            autoWidth: true,
	            bodyStyle: 'padding:5px 5px 0',
	            border: true,
	            frame: true,
	            fileUpload: true,
	            buttonAlign: 'center',
	            items:[new Ext.form.Hidden({
	            	id: 'menuId',//自身ID
	            	name: 'menu.id',
	            	value: id
	            }),
	            new Ext.form.TextField({
					fieldLabel: '父节点代码',
					id: 'menuPid',
	            	name: 'menu.pid',
	            	value: pid,
					anchor: '90%',
					allowBlank: true,
					readOnly: true
				}),
				new Ext.form.TextField({
					fieldLabel: cf_getRequiredItem('菜单名称'),
					anchor: '90%',
					name: 'menu.text',
					maxLength: 20,
					maxLengthText: '名称长度不可大于{0}字符',
					allowBlank: false,
					readOnly: false,
					value: menuName
				}),
				new Ext.form.TextField({
					fieldLabel: '连接地址',
					anchor: '90%',
					name: 'menu.url',
					emptyText: '示例：/jsp/menu/menuManager.jsp',
					maxLength: 999,
					maxLengthText: '地址长度不可大于{0}字符',
					allowBlank: true,
					readOnly: false,
					value: menuUrl
				}),
				new Ext.form.RadioGroup({// 单选按钮
					fieldLabel:'使用状态',
					anchor: '90%',
					columns: [50,50],// 列间距
					value: enableStatus,
           			items: [
           				{boxLabel: '启用', inputValue: 1, name: 'menu.enableStatus', checked: true},
           				{boxLabel: '禁用', inputValue: 0, name: 'menu.enableStatus'}
           			]
				}),
	            new Ext.form.ComboBox({  
	            	fieldLabel: 'Icon图标',
	            	name: 'menu.iconCls',
	            	value: iconCls,
		            //hiddenName: 'name',
		            valueField: 'name',
		            displayField: 'name',//url
		            editable: true,
		            allowBlank: false,
		            //msgTarget: 'under',//allowBlank展示方式
		            triggerAction: 'all',
		            anchor: '90%',
		            mode: 'remote',//数据加载模式
		            //minListWidth: 230,//下拉列表宽度
		            pageSize: 30,//每页显示的条数
		            store: new Ext.data.JsonStore({  
		                url: 'MenuAction!queryMenuIcon.do',
		                root: 'list',
		                totalProperty: 'total',
		                remoteSort: true,
		                fields: ['name', 'url']
		            }),
		            //queryParam: 'czp',
					tpl: '<table><tr><tpl for="."><td ext:qtip="{name}" class="x-combo-list-item"><img width=16 height=16 src="{url}" /></td><tpl if="xindex % 10 === 0"></tr><tr></tpl></tpl></tr></table>'
		        }),
				new Ext.form.TextArea({
					fieldLabel: '备注',
					anchor: '90%',
					name: 'menu.remark',
					allowBlank: true,
					readOnly: false,
					value: remark
				}),
				new Ext.form.Hidden({
	            	name: 'menu.menuType',
	            	value: menuType//1=用户菜单/2=设置菜单
	            })],
	            buttons: [{
	                text: '保存',
	                handler: function() {
	                    if(!(Ext.getCmp('formBatch').form.isValid())) {
	                    	return false;
	                    } else {
	                    	save(cudType);
	                    }
	                }
	            },{
	                text: '取消',
	                handler: function() {
	                    panel.hide('menuManager', function() {	// 淡入窗口
	                    	panel.close();						// 关闭
	                    }, true);
	                }
	            }]
	        });
    		
    		panel = new Ext.Window({
	            title: title,
	            id: 'optpanel',
	            layout: 'border',
	            width: 400,
	            height: 300,
	            modal: true,
	            closeAction: 'close',
	            resizable: false,
	            items: form,
	            constrain: true,//禁止窗口移出浏览器
				constrainHeader: true//禁止窗口移出浏览器
	        });
	        panel.show('menuManager');// 淡出窗口
	        
    	}
    	
    	/**
    	 * 保存Form表单数据
    	 * @param {Object} cudType 操作类型
    	 */
    	function save(cudType) {
    		Ext.getCmp('formBatch').getForm().submit({
				url: 'MenuAction!menuOperator.do',
				method: 'POST',
				submitEmptyText: false,
				params: {
					'cudType': cudType
	    		//	'optUserId': '1',
	    		//	'optUserName': '超级管理员'
				},
				success: function (result, request) {
					panel.hide('menuManager', function() {	// 淡入窗口
	                	panel.close();						// 关闭
	                	refresh();	// 刷新
	                }, true);
				},
				failure: function (result, request) {
					Ext.MessageBox.alert('提示', '操作失败!');
	            }
			});
    	}
    	
    	function refresh() {
    		var menuType = Ext.getCmp('menuType').getValue();
    		if(menuType == '1') {//1为"用户"菜单类型，2为"设置"菜单
    			Ext.getCmp('userMenuTree').root.reload();
    		} else {
    			Ext.getCmp('settingsMenuTree').root.reload();
    		}
    		
    		Ext.getCmp('formPanel').getForm().reset();
    	}
    	
    	var TreePanel = Ext.extend(Ext.tree.TreePanel, {
    		constructor: function(config) {
    			config = Ext.apply({
    				id: this.id,
                	useArrows: true,
			        autoScroll: false,
			        animate: true,
			        enableDD: true,//拖拽
			        containerScroll: true,
			        border: false,
			        rootVisible: false,
			        loader: new Ext.tree.TreeLoader(),
			        root: new Ext.tree.AsyncTreeNode({
				        id: '0',//pid
				        //text: '菜单',
				        draggable: false,// 根节点不容许拖动
				        expanded: false
				    }),
			        listeners: {
		    			beforeload: function(node) {//加载之前
                			this.loader.dataUrl = 'MenuAction!getMenuTreeByPid.do?menuType='+ this.menuType +'&pid='+ node.id;
				        },
				        beforeclick: function(node) {//点击事件
				        	Ext.getCmp('menuName').setValue(node.attributes.text);
				        	Ext.getCmp('nodeCode').setValue(node.attributes.id);
				        	Ext.getCmp('parentCode').setValue(node.attributes.pid);
				        	Ext.getCmp('linkAddress').setValue(node.attributes.url);
				        	Ext.getCmp('iconCls').setValue(node.attributes.iconCls);
				        	Ext.getCmp('status').setValue(node.attributes.enableStatus);
				        	Ext.getCmp('leaf').setValue(node.attributes.leaf);
				        	Ext.getCmp('remark').setValue(node.attributes.remark);
				        },
				        movenode: function(tree, node, oldParent, newParent, index) {//移动节点
				        	var childNodes = newParent.childNodes;
				        	var data = "[";
				        	for(var i = 0,len = childNodes.length; i < len; i++) {
				        		data = data + "{id:'"+ childNodes[i].attributes.id +"'}";
					            if (i < len - 1)	data = data + ",";
				        	}
				        	data = data + "]";
				        	
				        	Ext.Ajax.request({
			            		url: 'MenuAction!sortMenuNode.do',
			            		method: 'POST',
			            		params: {parentCode: newParent.id, jsonData: data},
			            		success: function() {
			            			if(newParent.id != oldParent.id && oldParent.id != 0) {//若将节点拖拽到外层后，旧父节点没有子节点时
						        		Ext.Ajax.request({//更新旧父节点
						            		url: 'MenuAction!updateParentLeaf.do',
						            		method: 'POST',
						            		params: {parentCode: oldParent.id},
						            		success: function() {},
						            		failure: function() {
						            	 		Ext.MessageBox.alert('提示', '父节点更新失败.');
						            	 	}
						            	});
						        	}
			            	 	},
			            		failure: function() {
			            	 		Ext.MessageBox.alert('提示', '操作失败');
			            	 	}
			            	});
			        	}
			        }
		        }, config);
		        TreePanel.superclass.constructor.call(this, config);
    		}
    	});
    </script>
  </head>
  
  <body>
  	<div id="menuManager"></div>
  </body>
</html>
